import { Ref } from 'vue'
/**
 * 各浏览器全屏方法Map
 * requestFullscreen 发出异步请求使元素进入全屏模式
 * exitFullscreen 让当前文档退出全屏模式
 * fullscreenElement 返回当前文档中正在以全屏模式显示的Element节点，如果没有使用全屏模式，则返回null
 * fullscreenEnabled 返回一个布尔值，表明浏览器是否支持全屏模式
 * fullscreenchange 事件当浏览器进入或离开全屏时触发
 * fullscreenerror Document.onfullscreenerror 属性是一个事件处理器用于处理 fullscreenchange 事件，在当前文档不能进入全屏模式，即使它被请求时触发
 */
const functionsMap = [
  [
    'requestFullscreen',
    'exitFullscreen',
    'fullscreenElement',
    'fullscreenEnabled',
    'fullscreenchange',
    'fullscreenerror'
  ],
  [
    'webkitRequestFullscreen',
    'webkitExitFullscreen',
    'webkitFullscreenElement',
    'webkitFullscreenEnabled',
    'webkitfullscreenchange',
    'webkitfullscreenerror'
  ],
  [
    'webkitRequestFullScreen',
    'webkitCancelFullScreen',
    'webkitCurrentFullScreenElement',
    'webkitCancelFullScreen',
    'webkitfullscreenchange',
    'webkitfullscreenerror'
  ],
  [
    'mozRequestFullScreen',
    'mozCancelFullScreen',
    'mozFullScreenElement',
    'mozFullScreenEnabled',
    'mozfullscreenchange',
    'mozfullscreenerror'
  ],
  [
    'msRequestFullscreen',
    'msExitFullscreen',
    'msFullscreenElement',
    'msFullscreenEnabled',
    'MSFullscreenChange',
    'MSFullscreenError'
  ]
]
type functionType = () => Promise<void>
type useFullscreenReturn = {
  isSupported: boolean
  isFullscreen: Ref<boolean>
  enter: functionType
  exit: functionType
  toggle: functionType
}
/**
 * @description: 全屏hooks
 * @param {*} target
 * @return {useFullscreenReturn}
 */
export default function useFullscreen(target?, msg = '当前浏览器不支持全屏') {
  const document = window.document
  const targetRef =
    target || (document == null ? void 0 : document.querySelector('html'))
  const isFullscreen = ref(false)
  let isSupported = false
  let map = functionsMap[0]
  if (!document) {
    isSupported = false
  } else {
    for (const m of functionsMap) {
      if (m[1] in document) {
        map = m
        isSupported = true
        break
      }
    }
  }
  if (!isSupported) {
    window.$message.warning(msg)
  }
  const [REQUEST, EXIT, ELEMENT, , EVENT] = map
  async function exit() {
    if (!isSupported) return
    if (document == null ? void 0 : document[ELEMENT]) await document[EXIT]()
    isFullscreen.value = false
  }
  async function enter() {
    if (!isSupported) return
    await exit()
    const target2 = unref(targetRef)
    if (target2) {
      await target2[REQUEST]()
      isFullscreen.value = true
    }
  }
  async function toggle() {
    if (isFullscreen.value) await exit()
    else await enter()
  }
  if (document) {
    document.addEventListener(
      EVENT,
      () => {
        isFullscreen.value = !!(document == null ? void 0 : document[ELEMENT])
      },
      false
    )
  }
  return {
    isSupported,
    isFullscreen,
    enter,
    exit,
    toggle
  } as useFullscreenReturn
}
